// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { withLogging, withAuth } from './middlewares'

// 定义中间件类型，提高类型安全性
type Middleware = (request: NextRequest) => NextResponse | null

// 中间件执行顺序数组
const middlewares: Middleware[] = [
    withAuth,         // 1. 认证检查
    withLogging,      // 2. 日志记录
]

export function middleware(request: NextRequest) {
    // 按顺序执行中间件
    for (const middleware of middlewares) {
        console.log('[Middleware] Executing:', middleware.name)
        const result = middleware(request)

        // 如果中间件返回了响应对象，立即终止并返回该响应
        if (result instanceof NextResponse) {
            return result
        }

        // 如果返回null，则继续执行下一个中间件
        // (这里不需要显式检查null，因为其他情况都已处理)
    }

    // 所有中间件执行完毕且没有返回响应，返回默认响应
    return NextResponse.next()
}

// 配置中间件匹配规则
export const config = {
    // 匹配所有路由，排除Next.js内部路径和特定API路由
    matcher: [
        '/((?!_next/static|_next/image|favicon.ico|api/auth).*)'
    ]
}
